package com.lanou3g.code0523.dynamic;

import com.lanou3g.code0523.permission.BaseFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@WebFilter(filterName = "RandomFilter", servletNames = "RandomServlet")
public class RandomFilter extends BaseFilter {
    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws Exception {
        // 思路
        // 当第一次访问资源的时候,根据servlet输出的结果
        // 生成一个html文件
        // 之后 只用这个html这个文件存在
        // 就不去访问servlet了 而是直接把这个html返回

        // 动态页面静态化,其实就是缓存
        // 真正会用redis做

        ServletContext app = request.getServletContext();
        String filePath = app.getRealPath("") + File.separator + "random.html";
        File file = new File(filePath);
        if (!file.exists()) {
            // 生成html文件
            MyResponse myResponse = new MyResponse(response, request.getServletContext());
            chain.doFilter(request, myResponse);
            myResponse.writeFile();
        }
        // 请求转发
        request.getRequestDispatcher("/random.html").forward(request, response);
    }
}
